//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include "ChannelCommand.h"
#include "ChannelMagic.h"
#include <stdlib.h>

ChannelCommand::ChannelCommand()
{
    m_dataSize = 0;
    m_channelNumber = 0;
    m_data = NULL;
    m_packageNumber = 0;
}

ChannelCommand::ChannelCommand(ChannelData* data)
{
    m_dataSize = data->GetDataSize();
    if (m_dataSize != 12) { // Can not be converted.
        m_dataSize = 0;
        m_channelNumber = 0;
        m_data = NULL;
        m_packageNumber = 0;
    }
    else {
        m_channelNumber = data->GetChannelNumber();
        if (m_dataSize <= 0) {
            m_data = NULL;
        }
        else {
            m_data = (char *)malloc(RoundSize(m_dataSize));
            if (m_data != NULL) {
                memcpy(m_data, data->GetData(), m_dataSize);
            }
        }
        m_packageNumber = data->GetPackageNumber();
    }
}

ChannelCommand::ChannelCommand(const ChannelCommand& cmd)
{
    m_dataSize = cmd.m_dataSize;
    m_channelNumber = cmd.m_channelNumber;
    if (cmd.m_dataSize <= 0) {
        m_data = NULL;
    }
    else {
        m_data = (char *)malloc(RoundSize(cmd.m_dataSize));
        if (m_data != NULL) {
            memcpy(m_data, cmd.m_data, cmd.m_dataSize);
        }
    }
    m_packageNumber = cmd.m_packageNumber;
}

ChannelCommand::ChannelCommand(unsigned int command)
{
    m_dataSize = 12;
    m_data = (char *)malloc(RoundSize(m_dataSize));
    m_channelNumber = 0;
    m_packageNumber = ChannelPackage::NextPackageNumber(); //?
    SetCommand(command);
    SetChannel(0);
    SetProperty(0);
}

ChannelCommand::ChannelCommand(unsigned int channel,
    unsigned int command)
{
    m_dataSize = 12;
    m_data = (char *)malloc(RoundSize(m_dataSize));
    m_channelNumber = 0;
    m_packageNumber = ChannelPackage::NextPackageNumber(); //?
    SetCommand(command);
    SetChannel(channel);
    SetProperty(0);
}

ChannelCommand::ChannelCommand(unsigned int channel,
    unsigned int command, unsigned int property)
{
    m_dataSize = 12;
    m_data = (char *)malloc(RoundSize(m_dataSize));
    m_channelNumber = 0;
    m_packageNumber = ChannelPackage::NextPackageNumber(); //?
    SetCommand(command);
    SetChannel(channel);
    SetProperty(property);
}

ChannelCommand::~ChannelCommand()
{
    if (m_data != NULL) {
        free(m_data);
    }
    m_data = NULL;
    m_dataSize = 0;
}
